<?php

class MyHelpers {
    protected static $instance = null;
    
    public static function getInstance() {
        if (!isset(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }

    static function testVar($var, $exits = false) {
        echo '<pre>';
        print_r($var);
        echo '</pre>';
        if ($exits) Yii::app()->end();

        return true;
    }

    public function convertMinute($minutes) {
        $hour   = floor($minutes / 60);
        $minute = $minutes % 60;

        return sprintf('%02d', $hour) . ':' . sprintf('%02d', $minute);
    }

    /**
     * Get Auto_increment value of Table
     * @param string $tblName
     * @return integer
     */
    public function getAutoIncrement($tblName) {
        $sql = 'SHOW TABLE STATUS WHERE `Name` = "' . $tblName . '"';

        $connection = Yii::app()->db;
        $command    = $connection->createCommand($sql);
        $row        = $command->queryRow();

        return (int) $row['Auto_increment'];
    }

    /**
     * CHUYỂN TIẾNG VIỆT CÓ DẤU SANG KHÔNG DẤU
     * @param string $str
     * @param string $char ký tự thay thế cho khoảng trắng, underline is default
     */
    public function convertSeoStr($str, $char = '-') {
        if (is_string($str)) {
            $unicode = array(
                'a' => array('á', 'à', 'ả', 'ã', 'ạ', 'ă', 'ắ', 'ặ', 'ằ', 'ẳ', 'ẵ', 'â', 'ấ', 'ầ', 'ẩ', 'ẫ', 'ậ'),
//                'A' => array('Á', 'À', 'Ả', 'Ã', 'Ạ', 'Ă', 'Ắ', 'Ặ', 'Ằ', 'Ẳ', 'Ẵ', 'Â', 'Ấ', 'Ầ', 'Ẩ', 'Ẫ', 'Ậ'),
                'd' => array('đ'),
//                'D' => array('Đ'),
                'e' => array('é', 'è', 'ẻ', 'ẽ', 'ẹ', 'ê', 'ế', 'ề', 'ể', 'ễ', 'ệ'),
//                'E' => array('É', 'È', 'Ẻ', 'Ẽ', 'Ẹ', 'Ê', 'Ế', 'Ề', 'Ể', 'Ễ', 'Ệ'),
                'i' => array('í', 'ì', 'ỉ', 'ĩ', 'ị'),
//                'I' => array('Í', 'Ì', 'Ỉ', 'Ĩ', 'Ị'),
                'o' => array('ó', 'ò', 'ỏ', 'õ', 'ọ', 'ô', 'ố', 'ồ', 'ổ', 'ỗ', 'ộ', 'ơ', 'ớ', 'ờ', 'ở', 'ỡ', 'ợ'),
//                'O' => array('Ó', 'Ò', 'Ỏ', 'Õ', 'Ọ', 'Ô', 'Ố', 'Ồ', 'Ổ', 'Ỗ', 'Ộ', 'Ơ', 'Ớ', 'Ờ', 'Ở', 'Ỡ', 'Ợ'),
                'u' => array('ú', 'ù', 'ủ', 'ũ', 'ụ', 'ư', 'ứ', 'ừ', 'ử', 'ữ', 'ự'),
//                'U' => array('Ú', 'Ù', 'Ủ', 'Ũ', 'Ụ', 'Ư', 'Ứ', 'Ừ', 'Ử', 'Ữ', 'Ự'),
                'y' => array('ý', 'ỳ', 'ỷ', 'ỹ', 'ỵ'),
//                'Y' => array('Ý', 'Ỳ', 'Ỷ', 'Ỹ', 'Ỵ'),
                '' => array('.', ',', ':', ';', '+', '-', '*', '/', '=',
                    '(', ')', '{', '}', '[', ']', '>', '<',
                    '~', '!', '@', '#', '$', '%', '^', '&', '?',
                    '\\', '\'', '`', '"',),
                $char => array(' '),
            );

            $str = mb_strtolower($str, 'UTF-8');
            
            foreach ($unicode as $non_uni => $uni) {
                foreach ($uni as $value) {
                    $str = str_replace($value, $non_uni, $str);
                }
            }
        }

        return trim($str, $char);
    }

    /**
     * Delete all files and subfolder use Iterator Interface
     * @param string $dirPath
     * @return boolean
     */
    public function deleteFolder($dirPath) {
        if (is_dir($dirPath)) {
            if (! $this->isDirEmpty($dirPath)) {
                $it    = new RecursiveDirectoryIterator($dirPath);
                $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
                foreach ($files as $file) {
                    if ($file->getFilename() === '.' || $file->getFilename() === '..') {
                        continue;
                    }
                    if ($file->isDir()) {
                        rmdir($file->getRealPath());
                    } else {
                        unlink($file->getRealPath());
                    }
                }
            }
            rmdir($dirPath);

            return TRUE;
        } else {
            return FALSE;
        }
    }
    
    public function isDirEmpty($dir) {
        if (! is_readable($dir))
            return NULL;
        $handle = opendir($dir);
        while (false !== ($entry  = readdir($handle))) {
            if ($entry != "." && $entry != "..") {
                return FALSE;
            }
        }
        closedir($handle);
        return TRUE;
    }
    
    /**
     * Generate random key with length in 8 character
     * @return string
     */
    public function generateKey() {
        $length = 8;
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $chars[rand(0, strlen($chars) - 1)];
        }
        
        return $randomString;
    }

    /**
     * Get extension from File name
     * @param string $fileName
     * @return string
     */
    public function getExtString($fileName) {
        $pos = strrpos($fileName, '.') + 1;
        return substr($fileName, $pos);
    }

    public function log($data, $fileLog = false) {
        if ( $fileLog ) {
            $logPath = Yii::getPathOfAlias('application.runtime') . '/test_var.html';
            if ( is_file($logPath) ) unlink($logPath);
            Yii::log(CVarDumper::dumpAsString($data, 10, true), 'info', 'test-var-1');
        } else {
            Yii::log(CVarDumper::dumpAsString($data, 10, false), 'info', 'test-var-2');
        }
        
    }
}